const express = require('express');
//创建路由对象
const router = express.Router();

const path = require('path');
const db = require('../db.js');

//显示 users.html 页面
// admin/user/users.html ==> /admin/user/users
router.get('/admin/user/users', (req, res) => {
    res.render(path.join(global.rootPath, 'view', 'admin/user/users.html'), req.session.userInfo);
})

//查询所有的管理员信息
router.get('/admin/user/getUser', (req, res) => {
    //1. 编写SQL语句
    const sql = 'select * from ali_admin';

    //2. 执行SQL语句
    db.query(sql, (err, result) => {
        if (err) {
            console.log(err);
            return res.send({code:201, message:"查询管理员信息失败"});
        }

        return res.send({code:200, message:"查询管理员信息成功", data: result});
    })
})

//显示添加新管理员页面
// admin/user/adduser.html ===> /admin/user/adduser
router.get('/admin/user/adduser', (req, res) => {
    res.render(path.join(global.rootPath, 'view', 'admin/user/adduser.html'), req.session.userInfo)
})

router.get('/admin/user/adduserdeal', (req, res) => {
    //1. 接收表单提交的数据
    const obj = {
        admin_email: req.query.email,
        admin_nickname: req.query.nickname,
        admin_pwd: req.query.password,
        admin_state: '激活'
    }

    //2. 编写SQL语句
    const sql = 'insert into ali_admin set ?';

    //3. 执行SQL语句
    db.query(sql, obj, (err, result) => {
        if (err) {
            console.log(err);
            return res.send({code:201, message:"添加新管理员失败"});
        }

        res.send({code:200, message:"添加新管理员成功"})
    })
})

//批量删除管理员
router.get('/admin/user/delusers', (req, res) => {
    //1. 接收数据
    const ids = req.query.ids;

    //2. 编写SQL语句
    const sql = `delete from ali_admin where admin_id in (${ids})`;

    //3. 执行SQL语句
    db.query(sql, (err, result) => {
        //4. 处理SQL执行结果
        if (err) {
            console.log(err);
            return res.send({code:201, message:"批量删除管理员失败"});
        }

        return res.send({code:200, message:"批量删除管理员成功"});
    })
})

//显示管理员编辑页
router.get('/admin/user/edituser', (req, res) => {
    const id = req.query.id;
    const sql = 'select * from ali_admin where admin_id=?';

    db.query(sql, id, (err, result) => {
        console.log(result);
        res.render(path.join(global.rootPath, 'view', 'admin/user/edituser.html'), result[0]);
    })
})

//修改管理员信息
router.get('/admin/user/modifyuser', (req, res) => {
    //1. 接收数据
    const obj = {
        admin_email: req.query.email,
        admin_nickname: req.query.nickname,
        admin_tel: req.query.tel,
        admin_state: req.query.state
    }

    //接收隐藏域中的admin_id
    const id = req.query.id;

    //2. 编写SQL语句
    const sql = 'update ali_admin set ? where admin_id=?';
    
    //3. 执行SQL语句
    db.query(sql, [obj, id], (err, result) => {
        //4. 处理SQL执行结果
        if (err) {
            console.log(err);
            return res.send({code:201, message:"修改管理员信息失败"})
        }

        return res.send({code:200, message:"修改管理员信息成功"});
    })
})

//导出
module.exports = router;